package com.datastructure.test.binaryadd;

public class BinaryAdd {

    public static void main(String[] args) {
        BinaryAdd binaryAdd = new BinaryAdd();
        String add = binaryAdd.binaryAdd("0", "1");
        System.out.println(add);
    }

    public String binaryAdd (String A, String B) {
        // write code here
        StringBuilder stringBuilder = new StringBuilder();
        int carry = 0;
        int aLength = A.length();
        int bLength = B.length();
        int[] aChar = new int[aLength];
        int[] bChar = new int[bLength];
        for (int i = 0; i < aLength; i++) {
            aChar[i]=A.charAt(aLength-i-1)-48;
        }
        for (int i = 0; i < bLength; i++) {
            bChar[i]=B.charAt(bLength-i-1)-48;
        }
        int i=0;
        for(;i<aLength&&i<bLength;i++){
            stringBuilder.append((aChar[i]+bChar[i]+carry)%2);
            carry= (aChar[i]+bChar[i]+carry)/2;
        }
        while (i<aLength){
            stringBuilder.append((aChar[i]+carry)%2);
            carry= (aChar[i]+carry)/2;
            i++;
        }
        while (i<bLength){
            stringBuilder.append((bChar[i]+carry)%2);
            carry= (bChar[i]+carry)/2;
            i++;
        }
        if(carry==1){
            stringBuilder.append(1);
        }
        return stringBuilder.reverse().toString();
    }
}
